from google.appengine.api import images
from google.appengine.api import urlfetch
from google.appengine.api import memcache, images, urlfetch


import entities, user, stats, tag
from libs import utils
from app import config
import string

MAX_ITEMS = 200

def wishById(wish_id):

    wish_key = entities.db.Key.from_path("Wish", wish_id)
        
    return entities.db.get(wish_key)

def listByUser(user_id):
    
    wishes = entities.Wish.all().filter("owner_id = ", user_id).order("-created").fetch(MAX_ITEMS)
    
    return wishes

def listLiked(user_id):
    
    #wishes = entities.Wish.all().filter("owner_id = ", user_id).order("-created").fetch(MAX_ITEMS)
    
    return wishes

def listByTag(tag, limit, platform_id):

    wishes = entities.Wish.all().filter("tags = ", tag).filter("platform_id = ", platform_id).fetch(limit)
    
    return wishes

def listNewest(limit, platform_id = None):
    
    if platform_id == None or platform_id == 0:
        wishes = entities.Wish.all().order("-created").fetch(limit)
    else:
        wishes = entities.Wish.all().filter("platform_id = ", platform_id).order("-created").fetch(limit)
    
    return wishes

def listRanked(limit, platform_id = None):
    
    if platform_id == None or platform_id == 0:
        wishes = entities.Wish.all().order("-likes").fetch(limit)
    else:
        wishes = entities.Wish.all().filter("platform_id = ", platform_id).order("-likes").fetch(limit)
    
    return wishes

def add(owner_id, title, description, link, reason_id, category_id, price_from, price_to, img_url, tags, platform_id):
    
    if len(title) < 3: return False
        
    image = getImage(img_url)
    
    price_from, price_to = utils.formatRange(price_from, price_to)
    
    tags_list = [string.capwords(x.strip().lower()) for x in tags.split(",")]
    
    wish = entities.Wish(owner_id = owner_id,
                   title = title,
                   description = description,
                   link = link,
                   tags = tags_list,
                   image = image,
                   reason_id = reason_id,
                   category_id = category_id,
                   platform_id = platform_id,
                   price_from = price_from,
                   price_to = price_to)
    wish.put()
    
    user.increment(owner_id, wishes = True)
    stats.increment(wishes = True)
    
    # invalidate mcache
    mc_key = "ws/u/0/" + owner_id
    data = memcache.delete(mc_key)
    
    tag.add(tags_list)
    
    return wish

def change(wish_id, user_id, title, description, link, reason_id, category_id, price_from, price_to, img_url, tags, status):
    
    wish = wishById(wish_id)
    
    if wish.owner_id != user_id: return False
    
    price_from, price_to = utils.formatRange(price_from, price_to)

    tags_list = [string.capwords(x.strip().lower()) for x in tags.split(",")]
    
    if wish.tags != tags_list:
        wish.tags = tags_list
        tag.add(tags_list)
    
    image = getImage(img_url)
    
    wish.title = title
    wish.description = description
    wish.link = link
    wish.price_from = price_from
    wish.price_to = price_to
    wish.reason_id = reason_id
    wish.category_id = category_id
    wish.status = status
    if image != None: wish.image = image
    
    wish.put()
    
    # invalidate cache
    mc_key = "ws/u/0/" + wish.owner_id
    data = memcache.delete(mc_key)
    
    return wish

def like(user_id, wish_id):
    
    wish = wishById(wish_id)
    liker = user.getById(user_id)
    
    if liker == None or wish == None or wish.owner_id == user_id: return False
    
    if user_id in wish.likers: return False
    
    wish.likers.insert(0, user_id)
    wish.likes = len(wish.likers)
    
    wish.put()    
    
    liker.likes.insert(0, str(wish_id))
    liker.put()
    
    return wish.likes

def copy(user_id, wish_id):
    
    wish = wishById(wish_id)
    
    if wish == None or wish.owner_id == user_id: return False
    
    new_wish = entities.Wish(owner_id = user_id,
                   title = wish.title,
                   description = wish.description,
                   link = wish.link,
                   tags = wish.tags,
                   image = wish.image,
                   reason_id = wish.reason_id,
                   platform_id = wish.platform_id,
                   price_from = wish.price_from,
                   price_to = wish.price_to)
    new_wish.put()
    
    return new_wish

def remove(wish_id, user_id):
    
    wish = wishById(wish_id)

    if wish == None or wish.owner_id != user_id: return False
    
    wish.status = 0

    wish.put()
    
    # invalidate cache
    mc_key = "ws/u/0/" + wish.owner_id
    data = memcache.delete(mc_key)
    
    user.decrement(user_id, wishes = True)
    
    return True

def getImage(img_url):
    
    image = None
    
    if len(img_url) < 10: return image
        
    fetched = False
    
    try:
        result = urlfetch.fetch(img_url)
        fetched = True
    except:
        fetched = False
        # pass
       
    try:     
        if fetched and result.status_code == 200:
            image_raw = result.content
            image = images.resize(image_data=image_raw, width=config.image_max_width, output_encoding=images.JPEG)
            image = images.im_feeling_lucky(image_data = image, output_encoding=images.JPEG)
    except:
        image = None
        # pass
        
    return image

def format(wishes):
    
    data = []

    for wish in wishes:
            
        if wish.status == 0: continue
            
        wish_id = wish.key().id()
        wish_ids = utils.id2ids(wish_id)
            
        if wish.reserver_id == None:
            reserved = False
        else: 
            reserved = True
                
        if wish.image != None:
            img_url = config.IMG_URL + "?id=" + wish_ids + "&nc=" + wish.updated.strftime("%d%m%y%H%M%S")
        else:
            img_url = ""
            
        wish.title = utils.xssescape(wish.title)
        if wish.description != None: wish.description = utils.xssescape(wish.description)
        #wish.link = utils.xssescape(wish.link)
        wish.tags = [utils.xssescape(t) for t in wish.tags]
                
        row = {"wish_id" : wish_ids, "price_from" : wish.price_from, "price_to" : wish.price_to, "reserved" : reserved, "title" : wish.title,
                   "link" : wish.link , "img_url" : img_url, "tags" : wish.tags, "owner_id" : wish.owner_id, "description" : wish.description,
                   "reason_id" : wish.reason_id, "status" : wish.status, "updated" : wish.updated.strftime("%d.%m.%y %H:%M:%S"), 
                   "likers" : wish.likers, "likes" : wish.likes, "category_id" : wish.category_id}
                        
        data.append(row)
        
    return data

